package com.heima.article.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.HotArticleService;
import com.heima.common.constants.article.ArticleConstants;
import com.heima.feigns.admin.AdminFeign;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.vo.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
/**
 * @作者 itcast
 * @创建日期 2021/4/26 11:06
 **/
@Service
@Slf4j
public class HotArticleServiceImpl implements HotArticleService {
    @Autowired
    ApArticleMapper apArticleMapper;
    @Autowired
    AdminFeign adminFeign;
    @Override
    public void computeHotArticle() {
        // 1. 以当前日期为准 查询近5天的文章数据
        // 计算5天之前的时间    yyyy-MM-dd hh:mm:ss
        String dateStr = LocalDateTime.now().minusDays(5).format(DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss"));
        List<ApArticle> apArticles = apArticleMapper.selectList(Wrappers.<ApArticle>lambdaQuery().ge(ApArticle::getPublishTime, dateStr));
        // 2. 计算文章的热度得分，将封装封装为 List<HotArticleVo>
        if(apArticles == null || apArticles.size() == 0){
            log.info("未查询到近5天的文章数据=========================================");
            return;
        }
        List<HotArticleVo> hotArticleVoList = computeHotArticleVo(apArticles);
        // 3. 按照频道缓存   缓存每个频道热度最高的前30条文章 存入redis
        // 3.1 通过feign查询频道列表
        ResponseResult responseResult = adminFeign.selectAllChannel();
        List<AdChannel>  channelList = JSONArray.parseArray(JSON.toJSONString(responseResult.getData()),AdChannel.class); // [{},{}]
        if(channelList == null || channelList.size()==0){
            log.info("未查询到频道信息=========================================");
            return;
        }
        for (AdChannel channel : channelList) {
            // 获取每一个频道的文章列表  按照得分的降序排序   取前30条文章
            List<HotArticleVo> hotArticleByChannel = hotArticleVoList.stream().filter(articleVo -> articleVo.getChannelId().equals(channel.getId()))
                    .sorted(Comparator.comparing(HotArticleVo::getScore).reversed())
                    .limit(30)
                    .collect(Collectors.toList());
            // 将热点文正存入到redis中
            cacheToRedisByKey(hotArticleByChannel,ArticleConstants.HOT_ARTICLE_FIRST_PAGE+channel.getId());
        }
        // 4. 默认频道缓存   缓存所有文章中热度最高的前30条文章 存入redis
        List<HotArticleVo> hotArticleByAll = hotArticleVoList.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed())
                .limit(30)
                .collect(Collectors.toList());
            // 将热点文正存入到redis中
            cacheToRedisByKey(hotArticleByAll,ArticleConstants.HOT_ARTICLE_FIRST_PAGE+ArticleConstants.DEFAULT_TAG);
    }
    @Autowired
    RedisTemplate<String,String> redisTemplate;
    private void cacheToRedisByKey(List<HotArticleVo> hotArticleVoList, String cacheKey) {
        // 按照key 将集合数据存入到redis中
        String hotArticleJson = JSON.toJSONString(hotArticleVoList);
        redisTemplate.opsForValue().set(cacheKey,hotArticleJson);
    }
    /**
     * 计算近5天  文章的得分
     * @param apArticles
     * @return
     */
    private List<HotArticleVo> computeHotArticleVo(List<ApArticle> apArticles) {
        List<HotArticleVo> hotArticleVoList = new ArrayList<>();
        // 1. 遍历文章集合
        for (ApArticle apArticle : apArticles) {
            // 2.  每篇文章  计算得分  封装vo对象
            Integer score = computeScore(apArticle);
            HotArticleVo hotArticleVo = new HotArticleVo();
            BeanUtils.copyProperties(apArticle,hotArticleVo);
            hotArticleVo.setScore(score);

            hotArticleVoList.add(hotArticleVo);
        }
        return hotArticleVoList;
    }

    private Integer computeScore(ApArticle apArticle) {
        Integer score = 0;
        // 点赞
        Integer likes = apArticle.getLikes()==null? 0:apArticle.getLikes();
        score += likes * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        // 阅读
        Integer views = apArticle.getViews()==null? 0:apArticle.getViews();
        score += views * ArticleConstants.HOT_ARTICLE_VIEW_WEIGHT;
        // 评论
        Integer comments = apArticle.getComment()==null? 0:apArticle.getComment();
        score += comments * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        // 收藏
        Integer collections = apArticle.getCollection()==null? 0:apArticle.getCollection();
        score += collections * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        return score;
    }


}
